﻿using PeshoMVC.Areas.Admin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace PeshoMVC.Areas.Admin.Controllers
{
    [Authorize(Roles = "admin")]
    public class AdvancedSearchController : Controller
    {
        private DataClassesDataContext db = new DataClassesDataContext();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(AdvancedSearchModel model)
        {
            return RedirectToAction("Result", model);
        }

        public ActionResult Result(AdvancedSearchModel model)
        {
            var query = QueryResult(model);
            ViewBag.Query = query;

            return View(query);
        }

        private List<UsersProfileView> QueryResult(AdvancedSearchModel model)
        {
            var jm =
                (from i in db.UsersProfileViews
                 where (((i.FirstName == model.FirstName && model.FirstName != null) || model.FirstName == null)
                 && ((i.LastName == model.LastName && model.LastName != null) || model.LastName == null)
                 && ((i.Birthday >= new DateTime(model.BirthdayFrom, 1, 1) && model.BirthdayFrom != null) || i.Birthday == null)
                 && ((i.Birthday <= new DateTime(model.BirthdayTo, 12, 31) && model.BirthdayTo != null) || i.Birthday == null)
                 && ((i.Gender == model.Gender && model.Gender != "default") || model.Gender == "default")
                 && ((i.HaveAPet == model.HaveAPet && model.HaveAPet != "default") || model.HaveAPet == "default")
                 && ((i.PetName == model.PetName && model.PetName != null) || model.PetName == null)
                 && ((i.PetGender == model.PetGender && model.PetGender != "default") || model.PetGender == "default"))
                 select i).ToList();

            return jm;
        }

        protected override void Dispose(bool disposing)
        {
            if (db != null)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}